package org.opens.netty.chatServer.server.handle;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.opens.netty.chatServer.message.ChatRequestMessage;
import org.opens.netty.chatServer.message.ChatResponseMessage;
import org.opens.netty.chatServer.server.session.SessionFactory;

@ChannelHandler.Sharable
public class ChatRequestMessageHandle extends SimpleChannelInboundHandler<ChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ChatRequestMessage msg) throws Exception {
        String toUsername = msg.getTo();
        Channel channel = SessionFactory.getSession().getChannel(toUsername);
        // 不为空表示在线
        if (channel != null) {
            ChatResponseMessage chatResponseMessage = new ChatResponseMessage(msg.getFrom(), msg.getContent());
            channel.writeAndFlush(chatResponseMessage);
        } else {
            ChatResponseMessage chatResponseMessage = new ChatResponseMessage(false, "对方用户不在线");
            ctx.writeAndFlush(chatResponseMessage);
        }
    }
}
